package com.gykfbxxh.imovie.utils;


import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.annotation.NonNull;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.app.utils.util.AppUtils;
import com.app.utils.util.StringUtils;
import com.gykfbxxh.imovie.AppApplication;
import com.gykfbxxh.imovie.config.AppConfigTools;
//import com.squareup.okhttp.OkHttpClient;

/**
 * 访问网络工具类
 * Created by xuxinghai on 2016/6/12.
 */
public class NetUtils {

    private static NetUtils sInstance;//唯一实例

    private RequestQueue mRequestQueue;//vollery请求

    private NetUtils(){
        getRequestQueue();//初始化网络工具
    }

    /**
     * 获取唯一实例
     * @return NetUtils
     */
    public static synchronized NetUtils getInstance(){
        if(sInstance == null){
            sInstance = new NetUtils();
        }
        return sInstance;
    }

    /**
     * 初始化访问网络的工具
     */
    public RequestQueue getRequestQueue(){
        if (mRequestQueue == null)
        {
//            mRequestQueue = Volley.newRequestQueue(AppUtils.getInstance().getContext(), new OkHttpStack(new OkHttpClient()));
            mRequestQueue = Volley.newRequestQueue(AppUtils.getInstance().getContext());
        }
        return mRequestQueue;
    }

    /**************以下是发送网络请求相关 start ****************/


    /**
     * 发送带标识的网络请求(方便断开请求)
     * @param request
     * @param tag
     */
    public void addRequest(@NonNull final Request<?> request, @NonNull final String tag){
        if(!TextUtils.isEmpty(tag)){
            request.setTag(tag);
        }

        addRequest(request);
    }

    /**
     * 发送网络请求
     *
     *
     * @param request 此参数不为空
     */
    public void addRequest(@NonNull final Request<?> request){
        request.setRetryPolicy(new DefaultRetryPolicy(6000,//默认超时时间，
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,//默认最大尝试次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        getRequestQueue().add(request);
    }


    /**
     * 退出指定的网络请求
     * @param tag
     */
    public void cancelAllRequests(@NonNull final String tag)
    {
        if(!TextUtils.isEmpty(tag)){
            getRequestQueue().cancelAll(tag);
        }

    }

    /**************以下是发送网络请求相关 end ****************/


    /**
     * 判断网络是否连接
     *
     * @param context
     * @return
     */
    public static boolean isConnected(Context context) {

        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (null != connectivity) {

            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (null != info && info.isConnected()) {
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断是否是wifi连接
     */
    public static boolean isWifi(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (cm == null || cm.getActiveNetworkInfo() == null) {
            return false;
        }
        return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;

    }

    /**
     * 打开网络设置界面
     */
    public static void openSetting(Activity activity) {
        Intent intent = new Intent("/");
        ComponentName cm = new ComponentName("com.android.settings",
                "com.android.settings.WirelessSettings");
        intent.setComponent(cm);
        intent.setAction("android.intent.action.VIEW");
        activity.startActivityForResult(intent, 0);
    }

    public static final int NETTYPE_NO = 0;//没网
    public static final int NETTYPE_WIFI = 0x01;//wifi
    public static final int NETTYPE_CM = 0x02;//移动网络


    /**
     * 获取当前网络类型
     *
     * @return 0：没有网络 1：WIFI网络 2：WAP网络 3：NET网络
     */
    public static int getNetworkType() {
        int netType = 0;
        ConnectivityManager connectivityManager = (ConnectivityManager) AppApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            String extraInfo = networkInfo.getExtraInfo();
            if (!StringUtils.isEmpty(extraInfo)) {
                netType = NETTYPE_CM;
            }
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = NETTYPE_WIFI;
        }
        return netType;
    }


    /**
     * 判断用户是否开启仅wifi加载
     *
     * @return 是否加载图片
     */
    public static boolean isLoadImage() {
        if (AppConfigTools.netType == NETTYPE_WIFI) {
            //当前网络为wifi
            return true;
        } else if (AppConfigTools.netType == NETTYPE_CM && AppConfigTools.isUseWifi) {
            //当前网络为移动网络并且开启了仅wifi加载图片
            return false;
        } else if (AppConfigTools.netType == NETTYPE_CM && !AppConfigTools.isUseWifi) {
            //当前网络为移动网络并且关闭了仅wifi加载图片
            return true;
        } else return true;
    }

    /**
     * 获取网络状态
     *
     * @param context
     * @return
     */
    public static String getNetworkType(Context context) {
        String strNetworkType = "";

        NetworkInfo networkInfo = null;
        try {
            networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (networkInfo == null) {
            return "2G";
        }
        if (networkInfo != null && networkInfo.isConnected()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                strNetworkType = "WIFI";
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                String _strSubTypeName = networkInfo.getSubtypeName();


                // TD-SCDMA   networkType is 17
                int networkType = networkInfo.getSubtype();
                switch (networkType) {
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
                        strNetworkType = "2G";
                        break;
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9 : replace by 14
                    case TelephonyManager.NETWORK_TYPE_EHRPD:  //api<11 : replace by 12
                    case TelephonyManager.NETWORK_TYPE_HSPAP:  //api<13 : replace by 15
                        strNetworkType = "3G";
                        break;
                    case TelephonyManager.NETWORK_TYPE_LTE:    //api<11 : replace by 13
                        strNetworkType = "4G";
                        break;
                    default:
                        // http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信 三种3G制式
                        if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA") || _strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                            strNetworkType = "3G";
                        } else {
                            strNetworkType = _strSubTypeName;
                        }
                        break;
                }
            }
        }

        return strNetworkType;
    }


}
